package com.junsi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.junsi.common.constant.UserConstants;
import com.junsi.common.core.domain.AjaxResult;
import com.junsi.common.core.domain.Ztree;
import com.junsi.common.core.text.Convert;
import com.junsi.common.enums.DbDialect;
import com.junsi.common.exception.BusinessException;
import com.junsi.common.utils.StringUtils;
import com.junsi.system.domain.SysArea;
import com.junsi.system.mapper.SysAreaMapper;
import com.junsi.system.mapper.SysCityMapper;
import com.junsi.system.service.ISysAreaService;
import com.junsi.system.vo.SysAreaCity;

/**
 * 地区 服务层实现
 * 
 * @author ymx
 * @date 2019-05-29
 */
@Service
public class SysAreaServiceImpl implements ISysAreaService 
{
	@Value("${pagehelper.helperDialect}")
	private String dbDialect;
    
	@Autowired
	private SysAreaMapper areaMapper;
	@Autowired
	private SysCityMapper sysCityMapper;

	/**
	 * 查询地区信息
	 * 
	 * @param areaCode 地区ID
	 * @return 地区信息
	 */
	@Override
	public SysArea selectAreaById(String areaCode)
	{
		return areaMapper.selectAreaById(areaCode);
	}

	/**
	 * 查询地区信息
	 * 
	 * @param areaCode 地区ID
	 * @return 地区信息
	 */
	@Override
	public List<SysArea> selectAreaByIds(String areaCode)
	{
		return areaMapper.selectAreaByIds(areaCode);
	}

	/**
	 * 查询区域树专用
	 * @param sysArea 地区信息
	 * @return
	 */
	@Override
	public List<Ztree> selectAreaTree(SysArea sysArea) {
		List<SysArea> sysAreaList= null;
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		sysAreaList= areaMapper.selectSysAreaList(sysArea);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		sysAreaList= areaMapper.selectSysAreaListOracle(sysArea);
    	} else {
    		return null;
    	}
		List<Ztree> ztrees = initZtree(sysAreaList);
		return ztrees;
	}

	/**
	 * 对象转区域树
	 *
	 * @param sysAreaList 区域列表
	 * @return 树结构列表
	 */
	public List<Ztree> initZtree(List<SysArea> sysAreaList)
	{

		List<Ztree> ztrees = new ArrayList<Ztree>();
		for (SysArea area : sysAreaList)
		{
			if (UserConstants.NORMAL.equals(area.getStatus()))
			{
				Ztree ztree = new Ztree();
				ztree.setId(area.getAreaCode().longValue());
				if(StringUtils.isNotNull(area.getParentCode())){
					ztree.setpId(area.getParentCode().longValue());
				}
				ztree.setName(area.getAreaName());
				ztree.setTitle(area.getAreaName());
				ztrees.add(ztree);
			}
		}
		return ztrees;
	}



	/**
	 * 查询地区信息
	 * 
	 * @param areaCode 父级ID
	 * @return 地区信息
	 */
	@Override
	public List<SysAreaCity> selectAreaAndCity(String areaCode)
	{
		return areaMapper.selectAreaAndCity(areaCode);
	}

	/**
	 * 查询地区信息
	 * 
	 * @param areaCode 父级ID
	 * @return 地区信息
	 */
	@Override
	public List<SysArea> selectAreaByPar(String areaCode)
	{
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		return areaMapper.selectAreaByPar(areaCode);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		return areaMapper.selectAreaByParOracle(areaCode);
    	} else {
    		return null;
    	}
	}

	/**
	 * 查询地区列表
	 * 
	 * @param area 地区信息
	 * @return 地区集合
	 */
	@Override
	public List<SysArea> selectAreaList(SysArea area)
	{
		List<SysArea> areaList = areaMapper.selectAreaList(new SysArea());
		int childs = 0;
		//计算所有下级区域数
		for (SysArea sysArea : areaList) {
			if (sysArea.getAreaCode() != 1) {
				childs += Integer.valueOf(sysArea.getChilds());
			}
			//岗位人员：0-未设置，1-已设置
			if ("0".equals(sysArea.getRole())) {
				sysArea.setRole("未设置");
			}else {
				sysArea.setRole("已设置");
			}
		}
		//给总部添加下级区域数
		for (SysArea sysArea : areaList) {
			if (sysArea.getAreaCode() == 1) {
				sysArea.setChilds(String.valueOf(childs));
			}
		}
		return areaList;
	}

	/**
	 * 查询地区列表
	 * 
	 * @param area 地区信息
	 * @return 地区集合
	 */
	@Override
	public List<SysArea> selectList(String areaCode)
	{
		List<SysArea> dataList = new ArrayList<SysArea>();
		List<SysArea> areaList = areaMapper.selectAreaLeve1();
		//判断新增、修改
		if (!"".equals(areaCode)) {
			//根据区域编码查询区域信息
			SysArea area = areaMapper.selectAreaById(areaCode);
			for (SysArea sysArea : areaList) {
				//给下拉框添加状态：1-已选择
				if (area.getParentCode().intValue() == sysArea.getAreaCode().intValue()) {
					sysArea.setUse(1);
				}
				dataList.add(sysArea);
			}
		}else {
			for (SysArea sysArea : areaList) {
				dataList.add(sysArea);
			}
		}
		return dataList;
	}

	/**
	 * 查询区域列表
	 * 
	 * @return 区域集合
	 */
	@Override
	public List<SysArea> selectAreaLeve2()
	{
		return areaMapper.selectAreaLeve2();
	}

	/**
	 * 新增地区
	 * 
	 * @param area 地区信息
	 * @return 结果
	 */
	@Override
	public int insertArea(SysArea area)
	{
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		return areaMapper.insertArea(area);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		return areaMapper.insertAreaOracle(area);
    	} else {
    		return 0;
    	}
	}

	/**
	 * 修改地区
	 * 
	 * @param area 地区信息
	 * @return 结果
	 */
	@Override
	public int updateArea(SysArea area)
	{
		return areaMapper.updateArea(area);
	}

	/**
	 * 删除地区对象
	 * 
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteAreaByIds(String ids)
	{
		return areaMapper.deleteAreaByIds(Convert.toStrArray(ids));
	}

	/**
	 * 新增区域城市关联
	 * @param areaCode 区域code
	 * @param cityCode 城市code
	 * @return 结果
	 */
	@Override
	public int insertAreaCity(SysAreaCity areaCity) {
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		return areaMapper.insertAreaCity(areaCity);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		return areaMapper.insertAreaCityOracle(areaCity);
    	} else {
    		return 0;
    	}
	}


	/**
	 * 删除地区对象
	 * 
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteById(String ids) throws BusinessException
	{
		String[] dictIds = Convert.toStrArray(ids);
		for (String id : dictIds) {
			List<SysArea> list = areaMapper.selectAreaByIds(id);
			for (SysArea sysArea : list) {
				if (!"0".equals(sysArea.getChilds())) {
					throw new BusinessException(String.format("存在下级区域,不能删除", sysArea.getAreaName()));
				}
			}
		}
		return areaMapper.deleteById(dictIds);
	}

	/**
	 * 查询区域列表
	 * @param code 区域编码
	 * @return 区域集合
	 */
	@Override
	public List<SysArea> leve3(List<SysArea> dataList, String code)
	{
		//默认显示全部区域
		if (null != code && !"".equals(code)) {
			//根据code查询区域集合
			for (SysArea sysArea : dataList) {
				if ("0".equals(sysArea.getStatus())) {
					sysArea.setStatus("启用");
				}else {
					sysArea.setStatus("停用");
				}
				if ("0".equals(sysArea.getRole())) {
					sysArea.setRole("未设置");
				}else {
					sysArea.setRole("已设置");
				}
				String name = "";
				//查询-省级数据
				List<SysAreaCity> proList = sysCityMapper.selectPro(String.valueOf(sysArea.getAreaCode()));
				for (int k = 0; k < proList.size(); k++) {
					SysAreaCity pro = proList.get(k);
					if (k != 0) {
						name += "<br>";
					}
					name += pro.getCityName() + "--";
					if ("2".equals(pro.getCheckChildState())) {
						name += "["+pro.getCityName()+"]";
					}else {
						String regName = "";
						//根据省查-市
						List<SysAreaCity> regList = sysCityMapper.selectChild(String.valueOf(sysArea.getAreaCode()), pro.getCityCode());
						for (int i = 0; i < regList.size(); i++) {
							SysAreaCity reg = regList.get(i);
							if (i != 0) {
								regName += "、";
							}
							if ("2".equals(reg.getCheckChildState())) {
								regName += reg.getCityName();
							}else {
								String cityName = reg.getCityName() + "--";
								//根据市查-区/县
								List<SysAreaCity> cityList = sysCityMapper.selectChild(String.valueOf(sysArea.getAreaCode()), reg.getCityCode());
								for (int j = 0; j < cityList.size(); j++) {
									SysAreaCity city = cityList.get(j);
									if (j != 0) {
										cityName += "/";
									}
									cityName += city.getCityName();
								}
								regName += cityName;
							}
						}
						name += "["+regName+"]";
					}
				}
				sysArea.setCity(name);
			}
			return dataList;
		}else {
			List<SysArea> head = null;
	    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
	    		head = areaMapper.selectAreaByPar("1");
	    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
	    		head = areaMapper.selectAreaByParOracle("1");
	    	} else {
	    		return null;
	    	}
			for (SysArea sysArea : head) {
				if ("0".equals(sysArea.getStatus())) {
					sysArea.setStatus("启用");
				}else {
					sysArea.setStatus("停用");
				}
				if ("0".equals(sysArea.getRole())) {
					sysArea.setRole("未设置");
				}else {
					sysArea.setRole("已设置");
				}
				List<SysAreaCity> city = areaMapper.selectAreaAndCity(String.valueOf(sysArea.getAreaCode()));
				if (null != city) {
					String name = "";
					for (SysAreaCity sysAreaCity : city) {
						StringBuffer str = new StringBuffer();
						name += sysAreaCity.getCityName()+str.append(";");
						sysArea.setCity(name);
					}
				}
			}
			return head;
		}
	}

	/**
	 * 新增保存
	 * @param areaCode 区域编码
	 * @param area 组织对象
	 * @return 结果
	 */
	@Override
	public AjaxResult addSave(String areaCode, SysArea area) throws BusinessException
	{	
		//判断新增还是修改
		if (null != areaCode && !"".equals(areaCode)) {
			SysArea value = areaMapper.selectAreaById(areaCode);
			value.setAreaName(area.getAreaName());
			value.setUpdateTime(new Date());
			List<SysArea> child = null;
	    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
	    		child = areaMapper.selectAreaByPar(areaCode);
	    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
	    		child = areaMapper.selectAreaByParOracle(areaCode);
	    	} else {
	    		return null;
	    	}
			for (SysArea sysArea : child) {
				sysArea.setAreaNames(area.getAreaName());
				areaMapper.updateArea(sysArea);
			}
			areaMapper.updateArea(value);
			return AjaxResult.success();
		}else {
			if (null != area && !"".equals(area.getAreaName())) {
				SysArea head = areaMapper.selectAreaById("1");
				//判断是否存在总部
				if (null != head) {
					area.setParentCode(head.getAreaCode());
					area.setAreaNames(head.getAreaName());
					area.setParentCode(head.getAreaCode());
					area.setCreateTime(new Date());
					area.setUpdateTime(new Date());
					area.setParentCodes((head.getParentCodes() + "," + head.getAreaCode()));
					area.setLvl(1);
				}else {
					area.setAreaCode(1);
					area.setParentCode(1);
					area.setParentCodes("0");
					area.setCreateTime(new Date());
					area.setUpdateTime(new Date());
					area.setLvl(0);
				}
			}else {
				return AjaxResult.error("请输入大区名称");
			}
		}
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		areaMapper.insertArea(area);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		areaMapper.insertAreaOracle(area);
    	}
		return AjaxResult.success();
	}

}
